package lukeer.fencing.lukeer.fencing.old;

import csproj.fencing.Move;
import csproj.fencing.Player;
import lukeer.fencing.Board;
import lukeer.fencing.BoardMove;
import lukeer.fencing.FencingException;
import lukeer.fencing.Piece;
import lukeer.fencing.lukeer.fencing.old.UserGUI;

import javax.swing.*;
import java.io.PrintStream;

import static java.lang.Thread.sleep;

/**
 * Created with IntelliJ IDEA.
 * User: Luke Richardson, Wafa M'Barek
 * Date: 30/09/12
 * Time: 13:07
 */
public class UserPlayer extends Thread implements Player, csproj.fencing.Piece {
    private static final int INVALID = -1;
    private static final int EMPTY = 0;
    private static final int WHITE = 1;
    private static final int BLACK = 2;

    private Board b;
    private UserGUI gui;
    private Piece.Type player = Piece.Type.BLACK;
    public boolean isUsersMove;

    public int getWinner() {
        b.calculateResult();
        return resultToInt(b.getResult());
    }

    public int init(int n, int p) {
        try {
            b = new Board(n);
        }
            catch (FencingException e) {
            return INVALID;
        }
        player = p==WHITE?Piece.Type.WHITE: Piece.Type.BLACK;
        SwingUtilities.invokeLater(gui = new UserGUI(b, player));
        return 0;
    }

    public synchronized Move makeMove() {
        try {
          while(gui.getLastmove()==null) {
                sleep(1000);
          }
            gui.registerMove();
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        BoardMove m = gui.getLastmove();
        try{
            placePiece(m);
        }
        catch(FencingException e) {
            System.err.println("Illegal move");
            System.exit(1);
        }
        return m.getMove();
    }


    private void placePiece(Move m) throws FencingException {
        BoardMove mw = new BoardMove(m);
        placePiece(mw);
    }

    private void placePiece(BoardMove mw) throws FencingException {
        b.setPiece(mw.getColumn(),mw.getRow(),mw.getType());
        if(mw.hasBarrier()) {
            b.setPiece(mw.getFColumn(),mw.getFRow(),mw.getHFence(),mw.getVFence());
        }
    }

    public int opponentMove(Move m) {
        try {
            placePiece(m);
        } catch(FencingException e){
            return -1;
        }

        return 0;
    }

    public void printBoard(PrintStream output) {
        output.print(b.getBoard());
    }

    private int resultToInt(Board.Result result) {
        switch(result) {
            case BLACK: return BLACK;
            case WHITE: return WHITE;
            case DRAW: return EMPTY;
            case NONE: return INVALID;
            default: return 5;
        }
    }
}
